﻿using airplane_server.Utils;
using Restful;
using server.Tool;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace server.Restful
{
    public class RestServiceInit
    {
        public void Init()
        {
            ThreadPool.SetMinThreads(100, 100); // 最小线程数
            ThreadPool.SetMaxThreads(1000, 1000); // 最大线程数  ，应该在代码什么地方设置

            // 获取本地 IP 地址
            string ipAdress = SelfHostHelper.GetHandlerIP();

            try
            {
                // 1. 创建高性能的 WebHttpBinding
                WebHttpBinding binding = CreateOptimizedWebHttpBinding();

                // 2. 启动第一个服务 (端口 8899)
                string url = "http://" + ipAdress + ":8899/";
                StartRestService<ServiceImp, IService>(url, binding);

                // 3. 启动第二个服务 (端口 8898)
                string url1 = "http://" + ipAdress + ":8898/";
                StartRestService<ServiceLifeImp, ILifeService>(url1, binding);

                // 4. 启动装备服务器 (端口 8897)
                string url2 = "http://" + ipAdress + ":8897/";
                StartRestService<ServiceknapsackImp, IknapsackService>(url2, binding);

                // 5. 启动管理服务器 (端口 8896)
                string adminUrl = "http://" + ipAdress + ":8896/";
                StartRestService<ManagerImp, IManager>(adminUrl, binding);

                Console.WriteLine("Web服务已开启...");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Web服务开启失败：{0}\r\n{1}", ex.Message, ex.StackTrace);
            }
        }

        /// <summary>
        /// 创建并配置高性能的 WebHttpBinding
        /// </summary>
        /// <returns>优化后的 WebHttpBinding</returns>
        private WebHttpBinding CreateOptimizedWebHttpBinding()
        {
            WebHttpBinding binding = new WebHttpBinding();

            // 1. 禁用安全（如果环境允许）以提高性能
            binding.Security.Mode = WebHttpSecurityMode.None;

            // 2. 设置较大的消息大小限制（避免大请求被拒绝）
            // 2. 设置较大的消息大小限制（虽然不需要大文件，但保持较大值以防万一）
            binding.MaxReceivedMessageSize = 10485760; // 10MB (比原来的2GB更合理)

            // 3. 调整读取器配额（适当增大但不过度）
            binding.ReaderQuotas.MaxDepth = 64;  // 比原来增大
            binding.ReaderQuotas.MaxStringContentLength = 1048576; // 1MB
            binding.ReaderQuotas.MaxArrayLength = 1048576; // 1MB
            binding.ReaderQuotas.MaxBytesPerRead = 65536; // 64KB
            binding.ReaderQuotas.MaxNameTableCharCount = 16384; // 16K

            // 4. 启用流式传输（适合大文件或流数据）
            // binding.TransferMode = TransferMode.Streamed;

            return binding;
        }

        /// <summary>
        /// 启动 RESTful 服务
        /// </summary>
        /// <typeparam name="TService">服务实现类</typeparam>
        /// <typeparam name="TContract">服务契约接口</typeparam>
        /// <param name="baseAddress">服务基地址</param>
        /// <param name="binding">绑定的配置</param>
        private void StartRestService<TService, TContract>(string baseAddress, WebHttpBinding binding)
            where TService : TContract
        {
            // 1. 创建 ServiceHost
            ServiceHost host = new ServiceHost(typeof(TService), new Uri(baseAddress));

            // 2. 添加服务端点，并附加 WebHttpBehavior（使服务支持 RESTful 风格）
            host.AddServiceEndpoint(typeof(TContract), binding, "").Behaviors.Add(new WebHttpBehavior());

            // 3. 设置授权管理器（如果需要）
            host.Authorization.ServiceAuthorizationManager = new MyServiceAuthorizationManager();

            // 4. 打开服务
            host.Open();
        }
    }
}